package com.better517na.elasticseach.handlers;



import com.better517na.elasticseach.context.ElasticSearchContext;
import com.better517na.elasticseach.elasticsearch.Index;
import com.better517na.elasticseach.utils.FileUtils;

import java.text.MessageFormat;
import java.util.Map;
import java.util.Set;

public class AbstractHandler {

    protected ElasticSearchContext context;

    public ElasticSearchContext getContext() {
        return context;
    }

    public void setContext(ElasticSearchContext context) {
        this.context = context;
    }

    protected void exportData(String o, int fileIndex){
        FileUtils.appendFile(context.getOutPut() + context.getFilePrefix() +  fileIndex + ".out",o);
    }

    protected String constructContent(Map<String, String> _docs, String template){
        Index index = context.getConsumer();
        Set<Map.Entry<String, String>> entries = _docs.entrySet();
        StringBuilder bulkBody = new StringBuilder();
        for (Map.Entry<String, String> entry: entries) {
            bulkBody.append(MessageFormat.format(template,index.getIndex(),index.getType(),entry.getKey()));
            bulkBody.append("\r\n").append(entry.getValue());
            bulkBody.append("\r\n");
            bulkBody.append("\r\n");
        }
        return bulkBody.toString();
    }
}
